const db = require('../db/db');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const config = require('../config');
const nodemailer = require('../services/email');

// 生成验证码


// 用户注册
exports.register = async (req, res) => {
  console.log('register body:', req.body);
  try {
    const { username, password, email } = req.body;
    
    // 检查用户名是否已存在
    const userRows = await db.query(
      'SELECT id FROM users WHERE username = ? OR email = ?',
      [username, email]
    );
    
    if (userRows.length > 0) {
      return res.status(400).json({
        success: false,
        message: '用户名或邮箱已存在'
      });
    }

    // 加密密码
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(password, saltRounds);

    // 开始数据库事务
    await db.beginTransaction();
    
    try {
      // 创建用户
      const result = await db.query(
        'INSERT INTO users (username, password, email) VALUES (?, ?, ?)',
        [username, hashedPassword, email]
      );
      
      const userId = result.insertId;
      
      // 创建默认名片夹
      const defaultFolders = [
        { name: '工作联系人', description: '工作相关的联系人' },
        { name: '客户信息', description: '客户和合作伙伴' },
        { name: '朋友', description: '个人朋友联系方式' },
        { name: '其他', description: '其他联系人' }
      ];
      
      for (const folder of defaultFolders) {
        await db.query(
          'INSERT INTO card_folders (user_id, name, description) VALUES (?, ?, ?)',
          [userId, folder.name, folder.description]
        );
      }
      
      // 提交事务
      await db.commit();
      
      res.json({
        success: true,
        message: '注册成功',
        userId: userId
      });
    } catch (error) {
      // 如果出错，回滚事务
      await db.rollback();
      throw error;
    }
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({
      success: false,
      message: '注册失败',
      error: error.message
    });
  }
};

// 用户登录
exports.login = async (req, res) => {
  try {
    const { username, password } = req.body;

    // 验证用户
    const userRows = await db.query(
      'SELECT id, username, password FROM users WHERE username = ?',
      [username]
    );
    
    if (!userRows || userRows.length === 0) {
      return res.status(400).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    const user = userRows[0];
    const passwordMatch = await bcrypt.compare(password, user.password);
    
    if (!passwordMatch) {
      return res.status(400).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 生成会话ID
    const sessionId = crypto.randomBytes(16).toString('hex');
    
    // 获取令牌过期时间
    const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24小时后

    // 保存会话信息到数据库 - 只保存会话ID，不存储完整JWT
    await db.query(
      'INSERT INTO user_sessions (user_id, token, expires_at) VALUES (?, ?, ?)',
      [user.id, sessionId, expiresAt]
    );

    // 生成JWT令牌，包含用户信息和会话ID
    const jwtPayload = {
      userId: user.id,
      username: user.username,
      sessionId: sessionId
    };
    
    const token = jwt.sign(jwtPayload, config.jwtSecret, {
      expiresIn: '24h' // 24小时后过期
    });

    // 返回登录成功信息
    res.json({
      success: true,
      token,
      expiresAt,
      userId: user.id,
      username: user.username
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: '登录失败',
      error: error.message
    });
  }
};

// 忘记密码
exports.forgotPassword = async (req, res) => {
  try {
    const { email } = req.body;
    
    // 检查邮箱是否存在
    const userRows = await db.query(
      'SELECT id, username FROM users WHERE email = ?',
      [email]
    );
    
    if (!userRows || userRows.length === 0) {
      return res.status(400).json({
        success: false,
        message: '该邮箱未注册'
      });
    }

    const user = userRows[0];
    const token = crypto.randomBytes(32).toString('hex');
    const expiresAt = new Date(Date.now() + 3600000); // 1小时后过期

    await db.query(
      'INSERT INTO password_reset_tokens (user_id, token, expires_at) VALUES (?, ?, ?)',
      [user.id, token, expiresAt]
    );

    // 发送重置密码邮件
    const resetLink = `http://${req.headers.host}/reset-password?token=${token}`;
    await nodemailer.sendResetPasswordEmail(email, resetLink);

    res.json({
      success: true,
      message: '重置密码链接已发送到您的邮箱'
    });
  } catch (error) {
    console.error('忘记密码错误:', error);
    res.status(500).json({
      success: false,
      message: '重置密码失败'
    });
  }
};

// 重置密码
exports.resetPassword = async (req, res) => {
  try {
    const { token, newPassword } = req.body;
    
    // 验证token
    const tokenRows = await db.query(
      'SELECT user_id FROM password_reset_tokens WHERE token = ? AND expires_at > NOW() AND used = FALSE',
      [token]
    );
    
    if (!tokenRows || tokenRows.length === 0) {
      return res.status(400).json({
        success: false,
        message: '无效或过期的重置链接'
      });
    }

    const userId = tokenRows[0].user_id;
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(newPassword, saltRounds);

    // 更新密码
    await db.query(
      'UPDATE users SET password = ? WHERE id = ?',
      [hashedPassword, userId]
    );

    // 标记token为已使用
    await db.query(
      'UPDATE password_reset_tokens SET used = TRUE WHERE token = ?',
      [token]
    );

    res.json({
      success: true,
      message: '密码重置成功'
    });
  } catch (error) {
    console.error('重置密码错误:', error);
    res.status(500).json({
      success: false,
      message: '密码重置失败'
    });
  }
};
